//
//  ActivityViewController.swift
//  iModern
//
//  Created by Ralf on 15/5/14.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit

//shrek 张义帅

class ActivityViewController: TableViewController
{
    let appDelegate     = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen          = UIScreen.mainScreen().bounds
    var articles        = NSMutableDictionary()
    let activityManager = ActivityManager()
    let articleManager  = ArticleManager()
    var max             = 0
    var offset          = 0
    var end             = false
    var activities      = NSMutableArray()
    var activityChannelSegmentedControl: UISegmentedControl?
    var searchButton:                    UIBarButtonItem?
    var postButton:                      UIBarButtonItem?

    override func viewDidLoad()
    {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "Refresh ShopActivity", object: nil)

        self.tableView.registerNib(UINib(nibName: "ActivityViewArticleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ARTICLE")
        self.tableView.registerNib(UINib(nibName: "ActivityViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
        //        self.tableView.registerNib(UINib(nibName: "ActivityViewTaskCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TASK")
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }

    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        MobClick.beginLogPageView("ActivityView")
        appDelegate.rootController.navigationItem.leftBarButtonItem = nil;
        initSearchButton()
        initPostButton()
        initActivityChannelSegmentedControl()

        if activities.count <= 0
        {
            loadData()
        }
    }

    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("ActivityView")
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return activities.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell: UITableViewCell?

        let index    = indexPath.row
        let activity = activities[index] as! NSMutableDictionary
        let article  = activity["article"] as! NSMutableDictionary
        let type     = article["type"] as! String

        if type == "Advertising"
        {
            let advertisingCell
            = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! ActivityViewAdvertisingCell
            advertisingCell.setData(activity)
            cell = advertisingCell
        }
        else
        {
            let articleCell = tableView.dequeueReusableCellWithIdentifier("ARTICLE", forIndexPath: indexPath) as! ActivityViewArticleCell
            articleCell.setData(activity)
            cell = articleCell
        }

        return cell!
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */

    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let screen = UIScreen.mainScreen().bounds

        let message       = activities.objectAtIndex(indexPath.row).objectForKey("article")?.objectForKey("message") as! NSString
        let messageHeight = sizeOfText(message).height
        return screen.size.width + 100 + messageHeight + 10
    }

    func initSearchButton()
    {
        if searchButton == nil
        {
            let image = UIImage(named: "Search-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
            searchButton = UIBarButtonItem(image: image, style: .Plain, target: self, action: "search:")
        }

        appDelegate.rootController.navigationItem.leftBarButtonItem = searchButton;
    }

    func initActivityChannelSegmentedControl()
    {
        if activityChannelSegmentedControl == nil
        {
            activityChannelSegmentedControl = UISegmentedControl(items: ["关注", "发现"])
            activityChannelSegmentedControl!.tintColor = UIColor.darkGrayColor()
            activityChannelSegmentedControl!.frame = CGRectMake(0, 0, 220, 28)
            activityChannelSegmentedControl!.selectedSegmentIndex = 0
            activityChannelSegmentedControl!.addTarget(self, action: "segmentSelected:", forControlEvents: .ValueChanged)
        }

        appDelegate.rootController.navigationItem.titleView = activityChannelSegmentedControl
    }

    @IBAction func segmentSelected(sender: UISegmentedControl)
    {
        reloadData(sender)
    }

    func getCategories() -> String!
    {
        return self.activityChannelSegmentedControl!.titleForSegmentAtIndex(self.activityChannelSegmentedControl!.selectedSegmentIndex)!
    }

    func loadData()
    {
        var rs: ResultSet?

        switch self.activityChannelSegmentedControl!.selectedSegmentIndex
        {
        case 1:
            if appDelegate.isLogged()
            {
                rs = activityManager.queryByFavorites(max, offset: offset, tag: nil)
            }
            else
            {
                activities.removeAllObjects()
                self.tableView.reloadData()
                return
            }
        case 0:
            if appDelegate.isLogged()
            {
                rs = activityManager.queryByFollowing(max, offset: offset, tag: nil)
            }
            else
            {
                activities.removeAllObjects()
                self.tableView.reloadData()
                return
            }
        default:
            break
        }


        if (rs == nil)
        {
            self.alertNetworkConnectionException()
            return
        }

        if (rs!.hasErrors())
        {
            self.alertWarningMessage(rs?.errorMessage)
            return
        }

        if (rs!.isEmpty())
        {
            end = true
        }
        else
        {
            activities.addObjectsFromArray(rs!.toMutableArray() as [AnyObject])
            offset = activities.count
        }

        self.tableView.reloadData()
    }

    @IBAction override func reloadData(sender: AnyObject!)
    {
        offset = 0
        end = false
        activities.removeAllObjects()
        loadData()

        super.reloadData(sender)
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let activity = activities[indexPath.row] as! NSMutableDictionary
        let article  = activity["article"] as! NSDictionary
        let type     = article["type"] as! String

        if type == "Article"
        {
            let controller = ArticlePageViewController()
            controller.activity = activity
            self.pushViewController(controller)
        }
        else
        {
            let controller = AdvertisingPageViewController()
            controller.activity = activity
            self.pushViewController(controller)
        }
    }

    @IBAction func search(sender: AnyObject)
    {
        let controller = ActivitySearchViewController()
        self.pushViewController(controller)
    }

    @IBAction func refresh(sender: AnyObject)
    {
        self.tableView.reloadData()
    }

    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()

        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20

        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left

        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
                          NSParagraphStyleAttributeName: paragraphStyle,
                          NSForegroundColorAttributeName: UIColor.darkGrayColor()]

        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }

    func initPostButton()
    {
        if postButton == nil
        {
            let image = UIImage(named: "Share-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
            postButton = UIBarButtonItem(image: image, style: .Plain, target: self, action: "loadCreateArticleViewController:")
        }

        appDelegate.rootController.navigationItem.rightBarButtonItem = postButton;
    }

    @IBAction func loadCreateArticleViewController(sender: AnyObject)
    {
        let controller = CreateAdvertisingViewController()
//        controller.contentType = "Article";
        pushViewController(controller)
    }
}
